package com.apes.scm.rcl.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.rcl.model.RclTask;
import com.apes.scm.rcl.repository.RclTaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @ClassName RclInstService
 * @Description TODO
 * @Author pengyb
 * @Date 2019/12/6 16:49
 * @Version 1.0
 **/
@Service("rclTaskService")
public class RclTaskService extends DomainService {
    @Autowired
    private RclTaskRepository rclTaskRepository;

    public RclTask save(SimpleRequest request) {
        RclTask task = request.getO(RclTask.class);
        if (task.isValid()) {
            if (task.isStarted()) {
                RclTask rclTask = rclTaskRepository.findOne(JpaDsl.toCriteriaByEq("started", true, "valid", true)).orElse(null);
                if (rclTask != null && !rclTask.getId().equals(task.getId()))
                    throw new RuntimeException("有效的开始任务只能存在一个，已存在任务:" + rclTask.getId());
            }
            if (task.isFinish()) {
                RclTask rclTask = rclTaskRepository.findOne(JpaDsl.toCriteriaByEq("finish", true, "valid", true)).orElse(null);
                if (rclTask != null && !rclTask.getId().equals(task.getId()))
                    throw new RuntimeException("有效的结束任务只能存在一个，已存在任务:" + rclTask.getId());
            }
        }
        if (task.getParent()!=null) {
            RclTask rclTask = rclTaskRepository.findOne(JpaDsl.toCriteriaByEq("parent.id", task.getParent().getId())).orElse(null);
            if (rclTask != null && !rclTask.getId().equals(task.getId()))
                throw new RuntimeException("有一个父类任务只能有一个子任务，已存在任务:" + rclTask.getId());
        }
        return rclTaskRepository.saveAndFlush(task);
    }

    public String delete(SimpleRequest request) {
        RclTask task = request.getO(RclTask.class);
        rclTaskRepository.delete(task);
        return "删除成功";
    }
}
